package com.px.lovepath.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.text.TextUtils;
import android.util.Log;

import com.px.lovepath.domain.config.ConfigInfo;
import com.px.lovepath.ui.home.CallRecord;
import com.px.lovepath.ui.home.SmsRecord;

public class Provider {

	private static final String TAG = Provider.class.getName();
	
	/**
	 * 获取相应的通话记录
	 */
	public static final ArrayList<CallRecord> getCallRecords(Context context) {
		ArrayList<CallRecord> result = new ArrayList<CallRecord>();
		try {
			String taPhoneNumber = ConfigInfo.get().getTaPhoneNumber();
			if (TextUtils.isEmpty(taPhoneNumber) == false) {
				ContentResolver resolver = context.getContentResolver();
				Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI,
			              null,
			              CallLog.Calls.NUMBER + " LIKE '%" + taPhoneNumber 
			              + "' AND " + CallLog.Calls.DURATION + " > 0", 
			              null, 
			              CallLog.Calls.DEFAULT_SORT_ORDER);
				
				if (cursor != null && cursor.moveToFirst()) {
					int dateIndex = cursor.getColumnIndex(CallLog.Calls.DATE);
					int durationIndex = cursor.getColumnIndex(CallLog.Calls.DURATION);
					int typeIndex = cursor.getColumnIndex(CallLog.Calls.TYPE);
					do {
						CallRecord temp = new CallRecord(
								new Date(cursor.getLong(dateIndex)), 
								cursor.getInt(durationIndex), 
								cursor.getInt(typeIndex));
						result.add(temp);
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.w(TAG, "Exception : " + e.getMessage());
		} finally {
			return result;
		}
	}
	
	/**
	 * 获取相应的短信记录
	 */
	public static final ArrayList<SmsRecord> getMessages(Context context) {
		ArrayList<SmsRecord> result = new ArrayList<SmsRecord>();
		try {
			String taPhoneNumber = ConfigInfo.get().getTaPhoneNumber();
			if (TextUtils.isEmpty(taPhoneNumber) == false) {
				ContentResolver resolver = context.getContentResolver();
				Uri uri = Uri.parse("content://sms/"); 
				String[] projection = new String[]{"date", "body", "type"}; 
				Cursor cursor = resolver.query(uri,
			              projection,
			              "address LIKE '%" + taPhoneNumber + "'", 
			              null, 
			              "date DESC" );
				
				if (cursor != null && cursor.moveToFirst()) {
					do {
						SmsRecord temp = new SmsRecord(
								new Date(cursor.getLong(0)), 
								cursor.getString(1), 
								cursor.getInt(2));
						result.add(temp);
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.w(TAG, "Exception : " + e.getMessage());
		} finally {
			return result;
		}
	}
}
